package com.micro.utils;

import com.micro.exception.InfoException;
import lombok.extern.slf4j.Slf4j;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author micro
 */
@Slf4j
public class MergeUtil {
    public static synchronized void merge(String source, String target) {
        try {
            File sourceFile = new File(source);
            File[] files1 = sourceFile.listFiles();
            if (files1 != null) {
                List<File> files = new ArrayList<>(Arrays.asList(files1));
                List<File> sortedList = new ArrayList<>();
                files.stream().sorted(Comparator.comparing(f -> Integer.valueOf(f.getName().substring(0, f.getName().indexOf("."))))).forEach(sortedList::add);
                //写入文件
                write(target, sortedList);
                TimeUnit.SECONDS.sleep(1);
                try {
                    transcodingByCopy(target);
                } catch (EncoderException e) {
                    log.info("文件转码异常：{}", e);
                    throw new InfoException("文件转码失败");
                }
            }
        } catch (Exception e) {
            log.info("文件合并异常：{}", e);
            throw new InfoException("合并文件失败");
        }
    }

    public static synchronized void write(String filePath, List<File> list) {
        File file1 = new File(filePath);
        if (file1.getParentFile().mkdirs()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            File[] catalogue = {null};
            list.stream().forEach(file -> {
                try {
                    if (catalogue[0] == null) {
                        catalogue[0] = file.getParentFile();
                    }
                    byte[] bytes = Files.readAllBytes(file.toPath());
                    fos.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //写出后删除文件
                if (file.delete()) {
                    log.info("删除缓存文件：{}",file.getName());
                }
            });
            //删除目录
            if (catalogue[0] != null) {
                if (catalogue[0].delete()) {
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 转码mp4
     *
     * @param target
     * @throws EncoderException
     */
    public static synchronized void transcodingByCopy(String target) throws EncoderException {
        Encoder encoder = new Encoder();
        File targetFile = new File(target);
        MultimediaObject mediaObject = new MultimediaObject(targetFile);
        EncodingAttributes attributes = new EncodingAttributes();
        VideoAttributes videoAttributes = new VideoAttributes();
        videoAttributes.setCodec(VideoAttributes.DIRECT_STREAM_COPY);
        AudioAttributes audioAttributes = new AudioAttributes();
        audioAttributes.setCodec(AudioAttributes.DIRECT_STREAM_COPY);
        attributes.setVideoAttributes(videoAttributes);
        attributes.setAudioAttributes(audioAttributes);
        File file = new File(target.substring(0, target.lastIndexOf(".")) + ".mp4");
        encoder.encode(mediaObject, file, attributes);
        //删除合并的文件
        if (targetFile.delete()) {
            return;
        }
    }
}
